package com.mrogrape.util;

import java.net.URL;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;

/**
 * @author Pavel Porvatov
 */
public class ResourceManager {
	private static final Logger logger = Logger.getLogger(ResourceManager.class.getName());

	private final Class<?> demoClass;
	private String bundleName = null;

	// Resource bundle for internationalized and accessible text
	private ResourceBundle bundle = null;

	/**
	 * 创建一个资源管理器。
	 * @param objClass
	 */
	public ResourceManager(Class<?> objClass) {
		this.demoClass = objClass;

		this.bundleName = objClass.getPackage().getName() + ".resources." + objClass.getSimpleName();

		try {
			this.bundle = ResourceBundle.getBundle(this.bundleName);
		} catch (MissingResourceException e) {
			ResourceManager.logger.log(Level.SEVERE, "Couldn't load bundle: " + this.bundleName);
		}
	}

	public String getString(String key) {
		return this.bundle != null ? this.bundle.getString(key) : key;
	}

	public String getString(String key, Object... params){
		String source = this.getString(key);
		if(StringUtils.isEmpty(source)){
			return source;
		}

		for(int i = 0; i<params.length; i++){
			if(params[i] == null){
				continue;
			}
			source = source.replace("{"+i+"}", params[i].toString());
		}

		return source;
	}

	public char getMnemonic(String key) {
		return (this.getString(key)).charAt(0);
	}

	public ImageIcon createImageIcon(String filename, String description) {
		String path = "resources/images/" + filename;

		URL imageURL = this.demoClass.getResource(path);

		if (imageURL == null) {
			ResourceManager.logger.log(Level.SEVERE, "unable to access image file: " + path);

			return null;
		} else {
			return new ImageIcon(imageURL, description);
		}
	}
}
